<template>
  <div class="reviews-list">
    <!-- 评分统计概览 -->
    <div v-if="stats" class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6 mb-6">
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- 总体评分 -->
        <div class="flex items-center gap-6">
          <div class="text-center">
            <div class="text-5xl font-bold text-gray-900 dark:text-white">
              {{ stats.averageRating.toFixed(1) }}
            </div>
            <RatingStars 
              :model-value="stats.averageRating" 
              :show-count="true"
              :count="stats.totalReviews"
            />
          </div>
          
          <!-- 评分分布 -->
          <div class="flex-1">
            <div v-for="star in [5, 4, 3, 2, 1]" :key="star" class="flex items-center gap-2 mb-1">
              <span class="text-sm text-gray-600 dark:text-gray-400 w-8">{{ star }}星</span>
              <div class="flex-1 bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                <div 
                  class="bg-yellow-400 h-2 rounded-full transition-all"
                  :style="{ width: `${getPercentage(star)}%` }"
                ></div>
              </div>
              <span class="text-sm text-gray-600 dark:text-gray-400 w-8 text-right">
                {{ stats.ratingDistribution[star] }}
              </span>
            </div>
          </div>
        </div>

        <!-- 多维度评分 -->
        <div v-if="hasDimensionRatings" class="space-y-3">
          <h4 class="font-medium text-gray-900 dark:text-white mb-3">多维度评分</h4>
          <div class="space-y-2">
            <div class="flex items-center justify-between">
              <span class="text-sm text-gray-600 dark:text-gray-400">性能</span>
              <RatingStars :model-value="stats.dimensionRatings.performance" :show-value="true" size="sm" />
            </div>
            <div class="flex items-center justify-between">
              <span class="text-sm text-gray-600 dark:text-gray-400">价格</span>
              <RatingStars :model-value="stats.dimensionRatings.price" :show-value="true" size="sm" />
            </div>
            <div class="flex items-center justify-between">
              <span class="text-sm text-gray-600 dark:text-gray-400">易用性</span>
              <RatingStars :model-value="stats.dimensionRatings.easeOfUse" :show-value="true" size="sm" />
            </div>
            <div class="flex items-center justify-between">
              <span class="text-sm text-gray-600 dark:text-gray-400">文档质量</span>
              <RatingStars :model-value="stats.dimensionRatings.documentation" :show-value="true" size="sm" />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和排序 -->
    <div class="flex flex-wrap items-center justify-between gap-4 mb-6">
      <div class="flex items-center gap-4">
        <select
          v-model="sortBy"
          class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-800 dark:text-white"
        >
          <option value="latest">最新</option>
          <option value="helpful">最有帮助</option>
          <option value="highest">评分最高</option>
          <option value="lowest">评分最低</option>
        </select>

        <select
          v-model="filterRating"
          class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg dark:bg-gray-800 dark:text-white"
        >
          <option value="0">所有评分</option>
          <option value="5">5星</option>
          <option value="4">4星及以上</option>
          <option value="3">3星及以上</option>
        </select>
      </div>

      <div class="text-sm text-gray-600 dark:text-gray-400">
        共 {{ total }} 条评论
      </div>
    </div>

    <!-- 评论列表 -->
    <div v-if="loading" class="text-center py-12">
      <div class="inline-block animate-spin rounded-full h-8 w-8 border-4 border-blue-600 border-t-transparent"></div>
      <p class="mt-4 text-gray-600 dark:text-gray-400">加载中...</p>
    </div>

    <div v-else-if="reviews.length === 0" class="text-center py-12 bg-white dark:bg-gray-800 rounded-lg">
      <p class="text-gray-600 dark:text-gray-400">暂无评论，快来发表第一条评论吧！</p>
    </div>

    <div v-else class="space-y-4">
      <div
        v-for="review in reviews"
        :key="review.id"
        class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-6"
      >
        <!-- 评论头部 -->
        <div class="flex items-start justify-between mb-4">
          <div class="flex items-start gap-3">
            <!-- 用户头像 -->
            <div class="w-10 h-10 rounded-full bg-gradient-to-r from-blue-500 to-purple-500 flex items-center justify-center text-white font-semibold">
              {{ review.user?.nickname?.charAt(0) || 'U' }}
            </div>
            
            <div>
              <div class="flex items-center gap-2">
                <span class="font-medium text-gray-900 dark:text-white">
                  {{ review.user?.nickname || '匿名用户' }}
                </span>
                <span v-if="review.isVerifiedPurchase" class="px-2 py-0.5 bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 text-xs rounded">
                  已验证
                </span>
                <span v-if="review.isFeatured" class="px-2 py-0.5 bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 text-xs rounded">
                  精选
                </span>
              </div>
              
              <div class="flex items-center gap-3 mt-1">
                <RatingStars :model-value="Number(review.rating)" />
                <span class="text-sm text-gray-500 dark:text-gray-400">
                  {{ formatDate(review.createdAt) }}
                </span>
              </div>
            </div>
          </div>

          <!-- 操作按钮（如果是自己的评论） -->
          <div v-if="canEdit(review)" class="flex gap-2">
            <button
              @click="$emit('edit', review)"
              class="text-sm text-blue-600 dark:text-blue-400 hover:underline"
            >
              编辑
            </button>
            <button
              @click="$emit('delete', review.id)"
              class="text-sm text-red-600 dark:text-red-400 hover:underline"
            >
              删除
            </button>
          </div>
        </div>

        <!-- 评论标题 -->
        <h4 v-if="review.title" class="font-semibold text-gray-900 dark:text-white mb-2">
          {{ review.title }}
        </h4>

        <!-- 评论内容 -->
        <p class="text-gray-700 dark:text-gray-300 mb-4 whitespace-pre-wrap">
          {{ review.content }}
        </p>

        <!-- 使用背景信息 -->
        <div v-if="review.useCase || review.teamSize || review.usageDuration" class="flex flex-wrap gap-2 mb-4">
          <span v-if="review.useCase" class="px-3 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-sm rounded-full">
            {{ review.useCase }}
          </span>
          <span v-if="review.teamSize" class="px-3 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-sm rounded-full">
            {{ review.teamSize }}
          </span>
          <span v-if="review.usageDuration" class="px-3 py-1 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 text-sm rounded-full">
            使用了 {{ review.usageDuration }}
          </span>
        </div>

        <!-- 有帮助按钮 -->
        <div class="flex items-center gap-4 pt-4 border-t border-gray-200 dark:border-gray-700">
          <button
            @click="$emit('markHelpful', review.id, true)"
            class="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5" />
            </svg>
            有帮助 ({{ review.helpfulCount }})
          </button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="totalPages > 1" class="flex justify-center gap-2 mt-6">
      <button
        v-for="page in totalPages"
        :key="page"
        @click="$emit('changePage', page)"
        class="px-4 py-2 rounded-lg"
        :class="
          page === currentPage
            ? 'bg-blue-600 text-white'
            : 'bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
        "
      >
        {{ page }}
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import RatingStars from './RatingStars.vue'
import type { Review, RatingStats } from '~/types'
import { useAuthStore } from '~/stores/auth'

const props = defineProps<{
  reviews: Review[]
  stats?: RatingStats
  loading?: boolean
  total: number
  currentPage: number
  totalPages: number
}>()

const emit = defineEmits<{
  edit: [review: Review]
  delete: [id: number]
  markHelpful: [id: number, helpful: boolean]
  changePage: [page: number]
  filterChange: [sortBy: string, filterRating: number]
}>()

const authStore = useAuthStore()
const sortBy = ref('latest')
const filterRating = ref(0)

const hasDimensionRatings = computed(() => {
  if (!props.stats) return false
  const { performance, price, easeOfUse, documentation } = props.stats.dimensionRatings
  return performance > 0 || price > 0 || easeOfUse > 0 || documentation > 0
})

const getPercentage = (star: number): number => {
  if (!props.stats || props.stats.totalReviews === 0) return 0
  const count = props.stats.ratingDistribution[star] ?? 0
  return (count / props.stats.totalReviews) * 100
}

const canEdit = (review: Review): boolean => {
  return authStore.isAuthenticated && authStore.user?.id === review.userId
}

const formatDate = (dateStr: string): string => {
  const date = new Date(dateStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 30) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN')
}

watch([sortBy, filterRating], () => {
  emit('filterChange', sortBy.value, filterRating.value)
})
</script>

